<?php
/**
 * Created by PhpStorm.
 * User: daniel.deng.haibiao
 * Date: 2017/11/29
 * Time: 16:58
 */

namespace app\common\controller;

use app\common\controller\Base as BaseController;
use think\Request;
use Firebase\JWT\JWT;
use think\Config;

class Auth extends BaseController
{
    public function _initialize()
    {
        parent::_initialize();
        if (strpos($this->beforeActionList['Authorization']['except'], strtolower($this->request->action()))) {
            $this->updateToken(false);
        }
    }

    protected $beforeActionList = [
        'Authorization' => ['except' => 'login,regist,receive']
    ];

    protected function Authorization()
    {
        $this->updateToken(true);
    }

    private function noAccess()
    {
        $this->customizedResult(false, null, "请登陆", "2000");
    }

    /*
     * 更新token
     * $requireToken 是否必须token
     **/
    private function updateToken($requireToken)
    {
        $token = Request::instance()->header('Token');
        if (isset($token)) {
            $secretKey = Config::get('customize')['secretKey'];
            // 定义载荷
            $currentTime = time();
            $expTime = $currentTime + 30 * 24 * 3600;//30天


            try {
                $decoded = JWT::decode($token, $secretKey, array('HS256'));
                if ($decoded->exp < $currentTime) {
                    if ($requireToken) {
                        $this->noAccess();
                    }
                } else {
                    $payload = array(
                        'iat' => $currentTime, // 有效期
                        'exp' => $expTime,
                        'data' => array(
                            'user_id' => $decoded->data->user_id
                        )
                    );
                    Request::instance()->bind('current_user', $decoded->data);
                    $privateToken = JWT::encode($payload, $secretKey);
                    header('Token:' . $privateToken);
                }
            } catch (\Exception    $e) {
                if ($requireToken) {
                    $this->noAccess();
                }
            }
        } else {
            if ($requireToken) {
                $this->noAccess();
            }
        }
    }

    /*
     * 创建token
     * */
    public function createToken($id)
    {
        $secretKey = Config::get('customize')['secretKey'];

        // 定义载荷
        $currentTime = time();
        $expTime = $currentTime + 30 * 24 * 3600;//30天

        try {
            $payload = array(
                'iat' => $currentTime, // 有效期
                'exp' => $expTime,
                'data' => array(
                    'user_id' => $id
                )
            );
            $privateToken = JWT::encode($payload, $secretKey);
            return $privateToken;
        } catch (\Exception    $e) {
            //
        }
    }
}